import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const DATA_DIR = path.resolve(__dirname, '../data/welcome');
const WELCOME_DIR = path.join(DATA_DIR, 'welcome_messages');

// 确保目录存在
(async () => {
  try {
    await fs.mkdir(DATA_DIR, { recursive: true });
    await fs.mkdir(WELCOME_DIR, { recursive: true });
  } catch (error) {
    console.error('创建目录失败:', error);
  }
})();

let isCooldown = false; // 冷却状态
const cooldownTime = 5000; // 5秒冷却时间
let lastTriggerTime = 0;

export class CustomNotificationPlugin extends plugin {
  constructor() {
    super({
      name: '[pippi]进群通知',
      dsc: '进群通知',
      event: 'message', // 监听消息事件
      priority: 500,
      rule: [
        { reg: "^#新增欢迎词(.+)$", fnc: 'addWelcomeMessage', permission: 'admin' },
        { reg: "^#删除欢迎词(.+)$", fnc: 'removeWelcomeMessage', permission: 'admin' },
        { reg: "^#查看欢迎词$", fnc: 'viewWelcomeMessages', permission: 'admin' }
      ]
    });

    // 监听群成员增加事件
    Bot.on('notice.group.increase', this.handleGroupIncrease.bind(this));
  }

  async addWelcomeMessage(e) {
    if (!this.checkAdminPermission(e)) return;

    const groupId = e.group_id.toString();
    const message = e.msg.match(/^#新增欢迎词(.+)$/)[1].trim();
    const groupFile = path.join(WELCOME_DIR, `${groupId}.json`);

    let welcomeMessages = await this.loadWelcomeMessages(groupFile);
    if (!welcomeMessages.includes(message)) {
      welcomeMessages.push(message);
      await this.saveWelcomeMessages(groupFile, welcomeMessages);
      await e.reply(`已添加欢迎词: ${message}`);
    } else {
      await e.reply(`欢迎词已存在: ${message}`);
    }
  }

  async removeWelcomeMessage(e) {
    if (!this.checkAdminPermission(e)) return;

    const groupId = e.group_id.toString();
    const message = e.msg.match(/^#删除欢迎词(.+)$/)[1].trim();
    const groupFile = path.join(WELCOME_DIR, `${groupId}.json`);

    let welcomeMessages = await this.loadWelcomeMessages(groupFile);
    const index = welcomeMessages.indexOf(message);
    if (index > -1) {
      welcomeMessages.splice(index, 1);
      await this.saveWelcomeMessages(groupFile, welcomeMessages);
      await e.reply(`已删除欢迎词: ${message}`);
    } else {
      await e.reply(`欢迎词不存在: ${message}`);
    }
  }

  async viewWelcomeMessages(e) {
    if (!this.checkAdminPermission(e)) return;

    const groupId = e.group_id.toString();
    const groupFile = path.join(WELCOME_DIR, `${groupId}.json`);

    let welcomeMessages = await this.loadWelcomeMessages(groupFile);
    if (welcomeMessages.length > 0) {
      const messageList = welcomeMessages.join('\n');
      await e.reply(`当前欢迎词:\n${messageList}`);
    } else {
      await e.reply('欢迎词列表为空。');
    }
  }

  checkAdminPermission(e) {
    if (!e.member.is_admin) {
      e.reply('只有群主或管理员可以使用此命令。');
      return false;
    }
    return true;
  }

  async loadWelcomeMessages(file) {
    try {
      if (await fs.access(file).then(() => true).catch(() => false)) {
        const data = await fs.readFile(file, 'utf-8');
        return JSON.parse(data);
      }
    } catch (error) {
      console.error('加载欢迎词列表失败:', error);
    }
    return [];
  }

  async saveWelcomeMessages(file, messages) {
    try {
      await fs.writeFile(file, JSON.stringify(messages, null, 2));
    } catch (error) {
      console.error('保存欢迎词列表失败:', error);
    }
  }

  async handleGroupIncrease(e) {
    const currentTime = Date.now();
    const timeDiff = currentTime - lastTriggerTime;

    if (isCooldown) {
      const remainingTime = cooldownTime - timeDiff;
      if (remainingTime > 0) {
        //console.log(`冷却中，剩余时间: ${Math.ceil(remainingTime / 1000)}秒`);
        return;
      }
    }

    isCooldown = true;
    lastTriggerTime = currentTime;

    if (e.user_id == e.bot.uin) return; // 如果是机器人自身的消息，则不进行处理

    const groupId = e.group_id.toString();
    const groupFile = path.join(WELCOME_DIR, `${groupId}.json`);
    let welcomeMessages = await this.loadWelcomeMessages(groupFile);

    if (welcomeMessages.length > 0) {
      const randomIndex = Math.floor(Math.random() * welcomeMessages.length);
      const msg = welcomeMessages[randomIndex];

      // 回复消息，@用户并发送图片和欢迎消息
      await Bot.pickGroup(e.group_id).sendMsg([
        segment.at(e.user_id),
        segment.image(`https://q1.qlogo.cn/g?b=qq&s=0&nk=${e.user_id}`),
        msg
      ]);
    }

    setTimeout(() => {
      isCooldown = false;
    }, cooldownTime);
  }
}

